// var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var unitRouter = require('./routes/unit');
var sortRouter = require('./routes/sort');
var wareHouseRouter = require('./routes/warehouse');
var inBoundRouter = require('./routes/inBound');
var outBoundRouter = require('./routes/outBound');
var goodRouter = require('./routes/good');
var noticeRouter = require('./routes/notice');
var app = express();

//token解析中间件 一定要在路由之前配置解析 Token 的中间件
const {expressjwt: expressJWT} = require('express-jwt')
//映入解密
const config = require('./config')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 注册全局中间件  链式调用 unless 方法，接收一个配置对象，path 字段设置一个正则表达式，表示不需要 token 身份认证的路由前缀。
app.use(expressJWT({
  // 加密时设置的密钥
  secret: config.jwtSecretKey,
  // 设置算法
  algorithms: ['HS256'],
  // 无token请求不进行解析，并且抛出异常
  // credentialsRequired: false
}).unless({
  path: [
    // '/users/add',
    '/api/users/login',
    {
      url: /^\/public\/.*/,
      methods: ['GET', 'POST']
    }
  ]
  // path: ['/users/login','/users']
}))

//封装错误处理函数
app.use((req, res, next) => {
  res.cc = function (err, success = false, data = {}, pageInfo = {}) {
    const body = pageInfo.page ? {
      success,
      data,
      pageInfo,
      message: err instanceof Error ? err.message : err
    } : {
      success,
      data,
      message: err instanceof Error ? err.message : err
    }
    res.send(body)
  }
  next()
})

// 错误中间件 当token失效时 返回信息
app.use((err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    res.status(401).send({
      success: false,
      data: {},
      message: '身份认证失败！'
    });
  }
});

app.use('/api/', indexRouter);
app.use('/api/users', usersRouter);
app.use('/api/unit', unitRouter);
app.use('/api/sort', sortRouter);
app.use('/api/inBound', inBoundRouter);
app.use('/api/outBound', outBoundRouter);
app.use('/api/warehouse', wareHouseRouter);
app.use('/api/good', goodRouter);
app.use('/api/notice', noticeRouter);

// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   next(createError(404));
// });
//
// // error handler
// app.use(function(err, req, res, next) {
//   // set locals, only providing error in development
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};
//
//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });

module.exports = app;
